/**
 * %%
 * %%
 */
package org.apache.flink.kubernetes.kubeclient.factory;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Base64;

import org.apache.commons.compress.utils.IOUtils;

import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.utils.IOHelpers;

/**
 * @类名: KubernetesClientFactory
 * @说明: 
 *
 * @author   leehom
 * @Date	 2024年4月23日 下午6:42:47
 * 修改记录：
 *
 * @see 	 
 */
public class KubernetesClientFactory {
	
	public static final String CONF_FILE = "conf/admin.conf";
	public static final String TOKEN_FILE = "conf/token";
	
	/***************token*****************/
	public static KubernetesClient clientByToken(String masterUrl) throws IOException {
		String token = loadTokenContent();
		return clientByToken(masterUrl, token);
	}
	
	public static KubernetesClient clientByToken(String masterUrl, String token) {
        Config config = new ConfigBuilder()
                .withTrustCerts(true)
                .withMasterUrl(masterUrl)
                .withOauthToken(token)
                .build();
        return new DefaultKubernetesClient(config);
	}

	private static String loadTokenContent() throws IOException {
		URL configUrl = KubernetesClientFactory.class.getClassLoader().getResource(TOKEN_FILE);
		return getKubeToken(new File(configUrl.getFile()));
	}

	private static String getKubeToken(File tokenFile) throws IOException {
		String tokenContent = null;
		try (FileReader reader = new FileReader(tokenFile)) {
			tokenContent = IOHelpers.readFully(reader);
		} catch (IOException e) {
			throw e;
		}
		return tokenContent;
	}
	
	/***************admin.conf****************/
	public static KubernetesClient clientByAdminConf() throws IOException {
		String adminContent = loadAdminConf();
		return clientByAdminConf(adminContent);
	}
	
	public static KubernetesClient clientByAdminConf(String adminContent) {
		Config config = Config.fromKubeconfig(adminContent);
		return new DefaultKubernetesClient(config);
	}
	
	private static String loadAdminConf() throws IOException {
		URL configUrl = KubernetesClientFactory.class.getClassLoader().getResource(CONF_FILE);
		return getKubeConfigContents(new File(configUrl.getFile()));
	}

	private static String getKubeConfigContents(File kubeConfigFile) throws IOException {
		String kubeconfigContents = null;
		try (FileReader reader = new FileReader(kubeConfigFile)) {
			kubeconfigContents = IOHelpers.readFully(reader);
		} catch (IOException e) {
			throw e;
		}
		return kubeconfigContents;
	}
	
	/***************证书****************/
	public static final String CA_CRT_FILE = "conf/cert/ca.crt";
	public static final String CLIENT_KEY_FILE = "conf/cert/client.key";
	public static final String CLIENT_CRT_FILE = "conf/cert/client.crt";
	
	public static KubernetesClient clientByCrt(String masterUrl) throws IOException {
		Config config;
        if(masterUrl.startsWith("https")) {
            final String caCrtData = loadFileContent(CA_CRT_FILE);
            final String clientKeyData = loadFileContent(CLIENT_KEY_FILE);
            // 注意：此处必须先用 Base64 对证书内容加密，否则会提示 input null
            final String clientCrtData = loadFileContent(CLIENT_CRT_FILE);
            //
            config = new ConfigBuilder().withMasterUrl(masterUrl)
                    .withTrustCerts(true)
                    .withCaCertData(caCrtData)
                    .withClientCertData(clientCrtData)
                    .withClientKeyData(clientKeyData)
                    .build();
        }else {
            config = new ConfigBuilder().withMasterUrl(masterUrl).build();
        }
        return new DefaultKubernetesClient(config);
	}
	
	private static String loadFileContent(String classPath) throws IOException {
		URL configUrl = KubernetesClientFactory.class.getClassLoader().getResource(classPath);
		return readFileContent(new File(configUrl.getFile()));
	}
	
	private static String readFileContent(File file) throws IOException {
		String content = null;
		try (FileReader reader = new FileReader(file)) {
			content = IOHelpers.readFully(reader);
		} catch (IOException e) {
			throw e;
		}
		return content;
	}
	
}
